package iconcurrent;

import java.util.concurrent.TimeUnit;

/**
 * <var>wait()</var> <var>notify()</var> - 两线程交替打印奇偶数
 * @author or2
 * @Description 使用两个线程交替打印奇偶数, 从 <var>0</var> 打印到 <var>99</var>
 * @create 2021年09月11日 时间: 9:51
 */
public class PrintOddAndEvenAlternately {
    private static int count = 0;
    private static final Object LOCK = new Object();

    public static void main(String[] args) throws InterruptedException {
        Runnable withSynchronized = () -> {
            while (count < 100) {
                synchronized (LOCK) {
                    System.out.println(Thread.currentThread().getName() + ": " + count++);
                    LOCK.notify();
                    try {
                        TimeUnit.SECONDS.sleep(1);
                        LOCK.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        };

        Thread thread1 = new Thread(withSynchronized, "偶数");
        Thread thread2 = new Thread(withSynchronized, "奇数");
//        启动两个线程, 让偶数先执行
        thread1.start();
        Thread.sleep(1);
        thread2.start();
//        唤醒最后一个线程锁
        thread1.join();
        synchronized (LOCK) {
            LOCK.notifyAll();
        }
    }
}
